package designPatterns.P11_代理模式_Proxy.P05_接口生成器InterfaceMaker;

import designPatterns.P11_代理模式_Proxy.P03_cglib_runoob.TargetObject;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InterfaceMaker;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestInterfaceMaker {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        InterfaceMaker im = new InterfaceMaker();
        //抽取某个类的方法生成接口方法
        im.add(TargetObject.class);
        Class<?> itarget = im.create();
        for (Method method : itarget.getMethods()) {
            System.out.println(method.getName());
        }
        //接口代理并设置代理接口方法拦截
        Object obj = Enhancer.create(Object.class, new Class[]{itarget}, new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                switch (method.getName()) {
                    case "method1":
                        System.out.println("filter method1");
                        return "method1";
                    case "method2":
                        System.out.println("filter method2");
                        return "method2";
                    case "method3":
                        System.out.println("filter method3");
                        return "method3";
                    default:
                        return "default";
                }
            }
        });
        Method method3 = obj.getClass().getMethod("method3", new Class[]{Integer.class});
        Object value3 = method3.invoke(obj, new Object[]{33});
        System.out.println(value3);
        Method method1 = obj.getClass().getMethod("method1", new Class[]{String.class});
        String value1 = (String) method1.invoke(obj, new Object[]{"abc"});
        System.out.println(value1);

    }
}
